import { Input, Tree } from 'antd';
import { ComponentProps, useMemo, useRef } from 'react';

import useSetState from '@/hooks/useSetState';
import { filterTree } from '@/utils/common';

import classes from './index.module.scss';
type Props = {
  title?: string;
} & ComponentProps<typeof Tree>;

const LeftTree: React.FC<Props> = ({
  title = '',
  blockNode = true,
  treeData = [],
  fieldNames = { title: 'title' },
  ...props
}) => {
  const [{ searchValue }, setState] = useSetState({ searchValue: '' });
  const treeKey = useRef(0);
  const key = useMemo(() => {
    return treeKey.current++;
  }, [treeData]);
  const filterTreeData = useMemo(() => {
    const title = fieldNames.title || 'title';
    const key = fieldNames.key || 'key';
    return searchValue
      ? filterTree(treeData, searchValue, {
          title: title,
          nodeRender(item) {
            const strTitle = item[title] as string;
            const index = strTitle.indexOf(searchValue);
            const beforeStr = strTitle.substring(0, index);
            const afterStr = strTitle.slice(index + searchValue.length);

            return index > -1 ? (
              <span key={key}>
                {beforeStr}
                <span style={{ color: 'var(--color-error)' }}>{searchValue}</span>
                {afterStr}
              </span>
            ) : (
              <span key={key}>{strTitle}</span>
            );
          },
        })
      : treeData;
  }, [fieldNames.key, fieldNames.title, searchValue, treeData]);

  return (
    <div className={classes.wrap}>
      <div className={classes.searchBox}>
        <Input
          placeholder="请输入关键词过滤"
          value={searchValue}
          onChange={(e) => setState({ searchValue: e.target.value })}
        />
      </div>
      <div className={classes.title}>
        {title}
        <div></div>
      </div>
      <div className={classes.content}>
        <div className={classes.overflow}>
          <Tree
            key={key}
            defaultExpandAll
            {...props}
            treeData={filterTreeData}
            blockNode={blockNode}
            fieldNames={fieldNames}
          />
        </div>
      </div>
    </div>
  );
};

export default LeftTree;
